package com.zhugang.week02;

/**
 * @program algorithms
 * @description: deleteDuplicates
 * @author: chanzhugang
 * @create: 2022/04/24 00:02
 */
public class DeleteDuplicates {

    /**
     * 83. 删除排序链表中的重复元素
     *
     * @param head
     * @return
     */
    public ListNode deleteDuplicates(ListNode head) {
        // 开辟新链表，遍历head，满足条件尾部插入
        ListNode newNode = new ListNode(-101, null);
        ListNode tail = newNode;
        ListNode p = head;
        while (p != null) {
            ListNode temp = p.next;
            if (p.val != tail.val) {
                // 此时p第一次出现，拼接在新链表尾部
                tail.next = p;
                tail = p;
                p.next = null;
            }
            p = temp;
        }
        return newNode.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

}